package com.authine.cloudpivot.common.extension.defaultextension;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.common.extension.client.dto.AuthenticationDTO;
import com.authine.cloudpivot.common.extension.utils.SsoUtils;
import com.authine.cloudpivot.common.organization.feign.OrganizationFeignService;
import com.authine.cloudpivot.common.organization.feign.UserFeignServiceI;
import com.authine.cloudpivot.common.organization.model.BaseUser;
import com.authine.cloudpivot.common.organization.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 单点登录服务扩展点默认扩展实现
 * <p>
 * 请勿修改任何类和方法的定义
 * <p>
 * 只需要在方法内部编写业务逻辑
 */
@Api(tags = "用户授权服务扩展点")
@Slf4j
@RestController
@RequestMapping("/authorization/v1")
public class UserAuthorizationController {

    @Autowired
    OrganizationFeignService organizationFeignService;

    @ApiOperation(value = "获取第三方授权对象查询云枢用户sourceId")
    @ApiImplicitParam(name = "authorization", value = "授权数据对象")
    @PostMapping("/get_source_id")
    public SingleResponse<String> getSourceId(@RequestBody AuthenticationDTO authorization) {
        log.info("二开单点登录...{}", JSON.toJSONString(authorization));

        // 同步用戶时，把第三方的唯一标识同步到用户表的sourceId ,corpId需要传组织id
        //code转sourceId
        //此时直接返回 code即可

        return SingleResponse.of(authorization.getCode());
    }

    @ApiOperation(value = "获取第三方首先信息查询云枢用户")
    @ApiImplicitParam(name = "authentication",value = "授权信息")
    @PostMapping("/get_user_authorization")
    public SingleResponse<BaseUser> getUserAuthorization(@RequestBody AuthenticationDTO authentication){
        log.info("===单点登录getUserAuthorization={}",authentication);
        String userId = SsoUtils.getUsername(authentication.getCode());
        SingleResponse<User> response = organizationFeignService.getUser(userId);
        log.info("===userId={},user={}",userId,response);
        User user = response.getData();
        log.info("===baseUserId={}",user.getBaseUserId());
        return organizationFeignService.getBaseUser(user.getBaseUserId());
    }

}
